import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClientService } from '../../../services/http-client.service';
import { CookieService } from "angular2-cookie/services/cookies.service";

@Component({
	selector: 'app-login',
	templateUrl: './login.component.html',
	styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
	public name: any;
	public PostBody: any = {
		UserId: "",
		PassWord: "",
		Role: "user"
	};
	constructor(
		public httpClient: HttpClientService,
		public router: Router,
		public cookie: CookieService
	) { }
	ngOnInit() {
		window['$']('#user').addClass('start');
		this.cookie.put('name', '成成');
		this.cookie.put('age', '20');
		this.name = this.cookie.get('age');
		console.log(this.name)
	}
	login() {
		let that = this;
		console.log(JSON.stringify(this.PostBody));
		this.httpClient.post('api/v1/users/login', that.PostBody, {
			isAuthHttp: false
		}).subscribe(data => {
			if (data) {
				window['swal']('提示', '登录成功', 'success');
				sessionStorage.setItem('token', data.token);
				sessionStorage.setItem('Role', data.user.Role);
				sessionStorage.setItem('UserId', data.user.UserId);
				sessionStorage.setItem('PassWord', data.user.PassWord);
				sessionStorage.setItem('UserName', data.user.UserName);
				sessionStorage.setItem('updatedAt', data.user.updatedAt);
				if (data.user.Role == 'user') {
					let post: any = {
						where: {
							StudentId: data.user.UserId
						}
					}
					that.httpClient.post('api/v1/studentlists/view', post).subscribe(data => {
						if (data) {
							sessionStorage.setItem('TeacherId', data.TeacherId);
							that.router.navigateByUrl("pages/student/select-title");
						}
					})
				} else if (data.user.Role == 'teach') {
					that.router.navigateByUrl("pages/teacher/stu-manage");
				} else if (data.user.Role == 'admin') {
					that.router.navigateByUrl("pages/manage/user-manage");
				}
			} else {
				window['swal']('提示', '用户名或密码不正确，请重新登录', 'info');
			}
		})
		// sessionStorage.setItem('token', 'token');
		// sessionStorage.setItem('Role', 'admin');
		// that.router.navigateByUrl("pages/manage/user-manage");
	}
	// 角色选择
	CheckRole(Role) {
		window['$']('.btn-group .btn').removeClass('start');
		if (Role == 'user') {
			this.PostBody.Role = "user";
			window['$']('#user').addClass('start');
		} else if (Role == 'teach') {
			this.PostBody.Role = "teach";
			window['$']('#teach').addClass('start');
		} else {
			this.PostBody.Role = "admin";
			window['$']('#admin').addClass('start');
		}
		// console.log("Role = " + this.PostBody.Role);
	}
}
